package com.xinsoft.controller.mes;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.MesWorkTeamParam;
import com.xinsoft.entity.dto.ScmStockMoveDTO;
import com.xinsoft.entity.dto.ScmStockMoveParam;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.MesWorkTeamVo;
import com.xinsoft.entity.vo.ScmProduceReturnPageVo;
import com.xinsoft.entity.vo.ScmStockMovePageVo;
import com.xinsoft.entity.vo.ScmStockMoveVo;
import com.xinsoft.service.*;
import com.xinsoft.utils.ExcelUtils;
import com.xinsoft.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 班组配置
 */
@RestController
@Api(value = "MesWorkDateController", tags = {"班组配置控制层"})
@RequestMapping("/mes/workTeam")
public class MesWorkTeamController {

    @Autowired
    private MesWorkTeamService mesWorkTeamService;
    @Autowired
    private MesTeamUserRefService mesTeamUserRefService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ScmStockMoveService scmStockMoveService;

    /**
     * 保存班组
     */
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("保存班组")
    public Response<?> add(@RequestBody MesWorkTeam dto) {
        List<MesWorkTeam> list = mesWorkTeamService.list(new QueryWrapper<MesWorkTeam>().eq(
                "team_code", dto.getTeamCode())
                .or().eq("team_name", dto.getTeamName()));
        if (list.size() > 0) {
            return Response.fail("班组名称或编码重复");
        }
        dto.setAuditStatus(Const.AUDIT_STATUS_WAIT);
        mesWorkTeamService.saveOrUpdate(dto);
        if (dto.getRefVOS().size() > 0) {
            for (int i = 0; i < dto.getRefVOS().size(); i++) {
                dto.getRefVOS().get(i).setTeamId(dto.getId());
            }
            mesTeamUserRefService.saveBatch(dto.getRefVOS());
        }
        return Response.succeed();
    }

    /**
     * 编辑班组
     */
    @PostMapping("/edit")
    @ApiOperation("编辑班组")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> edit(@RequestBody MesWorkTeam dto) {
        List<MesWorkTeam> list = mesWorkTeamService.list(new QueryWrapper<MesWorkTeam>()
                .eq("team_code", dto.getTeamCode()).ne("id", dto.getId())
                .or().eq("team_name", dto.getTeamName()).ne("id", dto.getId()));
        if (list.size() > 0) {
            return Response.fail("存在班组名称或编码重复");
        }
        dto.setAuditStatus(Const.AUDIT_STATUS_WAIT);
        mesWorkTeamService.saveOrUpdate(dto);
        if (dto.getRefVOS().size() > 0) {
            mesTeamUserRefService.remove(new LambdaQueryWrapper<MesTeamUserRef>().eq(MesTeamUserRef::getTeamId, dto.getId()));
            for (int i = 0; i < dto.getRefVOS().size(); i++) {
                dto.getRefVOS().get(i).setTeamId(dto.getId());
            }
            mesTeamUserRefService.saveBatch(dto.getRefVOS());
        }
        return Response.succeed();
    }


    /**
     * 班组人员配置
     */
    @PostMapping("/saveUsers")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> saveUsers(@RequestBody List<MesTeamUserRef> refVOS) {
        Integer teamId = refVOS.get(0).getTeamId();
        mesTeamUserRefService.remove(new LambdaQueryWrapper<MesTeamUserRef>().eq(MesTeamUserRef::getTeamId, teamId));
        mesTeamUserRefService.saveBatch(refVOS);
        return Response.succeed();
    }

    /**
     * 审核
     */
    @PostMapping("/audit")
    public Response<?> audit(@RequestBody List<Integer> ids) {
        List<MesWorkTeam> workTeamDOS = mesWorkTeamService.list(new LambdaQueryWrapper<MesWorkTeam>().in(MesWorkTeam::getId, ids));
        List<MesWorkTeam> errors = workTeamDOS.stream().filter(item -> Const.AUDIT_STATUS_NORMAL.equals(item.getAuditStatus())).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(errors)) {
            return Response.fail("请勿勾选已审核状态班组！");
        }
        List<MesWorkTeam> workTeamVOS = ids.stream().map(item -> {
            MesWorkTeam mesWorkTeam = new MesWorkTeam();
            mesWorkTeam.setId(item);
            mesWorkTeam.setAuditStatus(Const.AUDIT_STATUS_NORMAL);
            mesWorkTeam.setAuditId(TokenUtil.getUserId());
            return mesWorkTeam;
        }).collect(Collectors.toList());
        mesWorkTeamService.updateBatchById(workTeamVOS);
        return Response.succeed();
    }

    /**
     * 反审核
     */
    @PostMapping("/reverseAudit")
    public Response<?> reverseAudit(@RequestBody List<Integer> ids) {
        List<MesWorkTeam> workTeamDOS = mesWorkTeamService.list(new LambdaQueryWrapper<MesWorkTeam>().in(MesWorkTeam::getId, ids));
        List<MesWorkTeam> errors = workTeamDOS.stream().filter(item -> Const.DEL_FLAG_NORMAL.equals(item.getAuditStatus())).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(errors)) {
            return Response.fail("请勿勾选未审核状态班组！");
        }
        List<MesWorkTeam> workTeamVOS = ids.stream().map(item -> {
            MesWorkTeam mesWorkTeam = new MesWorkTeam();
            mesWorkTeam.setId(item);
            mesWorkTeam.setAuditStatus(Const.DEL_FLAG_NORMAL);
            return mesWorkTeam;
        }).collect(Collectors.toList());
        mesWorkTeamService.updateBatchById(workTeamVOS);
        return Response.succeed();
    }

    /**
     * 分页
     */
    @PostMapping("/pageList")
    public Response<?> pageList(@RequestBody MesWorkTeamParam param) {
        Page<MesWorkTeam> page = new Page<MesWorkTeam>(param.getCurrentPage(), param.getPageSize());
        LambdaQueryWrapper<MesWorkTeam> wrapper = new LambdaQueryWrapper<MesWorkTeam>().eq(ObjectUtil.isNotEmpty(param.getTeamName()), MesWorkTeam::getTeamName, param.getTeamName());
        IPage<MesWorkTeam> result = mesWorkTeamService.page(page, wrapper);
        if (result.getRecords().size() > 0) {
            List<MesWorkTeam> list = result.getRecords();
            // 翻译编组人员
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).getLeader() != null){
                    SysUser sysUser = sysUserService.getById(list.get(i).getLeader());
                    list.get(i).setLeaderName(sysUser.getRealName());
                }
                // 获取班组所有人员
                List<MesTeamUserRef> mesTeamUserRefs = mesTeamUserRefService.list(
                        new QueryWrapper<MesTeamUserRef>().eq("team_id", list.get(i).getId()));
                if (mesTeamUserRefs.size() > 0) {
                    for (int j = 0; j < mesTeamUserRefs.size(); j++) {
                        SysUser sysUser = sysUserService.getById(mesTeamUserRefs.get(j).getUserId());
                        if (list.get(i).getTeamUsers() == null) {
                            if(sysUser == null){
                                list.get(i).setTeamUsers("被删除的用户uid:" + mesTeamUserRefs.get(j).getUserId() + ";");
                            }else{
                                list.get(i).setTeamUsers(sysUser.getRealName() + ";");
                            }
                        } else {
                            if(sysUser == null){
                                list.get(i).setTeamUsers(list.get(i).getTeamUsers() + "被删除的用户uid:" + mesTeamUserRefs.get(j).getUserId() + ";");
                            }else{
                                list.get(i).setTeamUsers(list.get(i).getTeamUsers() + sysUser.getRealName() + ";");
                            }
                        }
                    }
                }
            }
        }
        return Response.succeed(result);
    }

    /**
     * 分页
     */
    @GetMapping("/tree")
    public Response<?> tree() {
        List<MesWorkTeam> workTeamList = mesWorkTeamService.list();
        if (workTeamList.size() > 0) {
            // 翻译编组人员
            for (int i = 0; i < workTeamList.size(); i++) {
                // 获取班组所有人员
                List<MesTeamUserRef> mesTeamUserRefs = mesTeamUserRefService.list(
                        new QueryWrapper<MesTeamUserRef>().eq("team_id", workTeamList.get(i).getId()));
                if (mesTeamUserRefs.size() > 0) {
                    for (int j = 0; j < mesTeamUserRefs.size(); j++) {
                        SysUser sysUser = sysUserService.getById(mesTeamUserRefs.get(j).getUserId());
                        if (ObjectUtil.isEmpty(sysUser)) continue;
                        mesTeamUserRefs.get(j).setUserName(sysUser.getRealName());
                    }
                }
                workTeamList.get(i).setRefVOS(mesTeamUserRefs);
            }
        }
        return Response.succeed(workTeamList);
    }

    /**
     * 获取班组人员
     */
    @GetMapping("/detail")
    public Response<List> detail(@RequestParam(value = "id") Integer id) {
        List userVOS = new ArrayList();
        List<MesTeamUserRef> userRefs = mesTeamUserRefService.list(new LambdaQueryWrapper<MesTeamUserRef>().eq(MesTeamUserRef::getTeamId, id));
        if (ObjectUtil.isEmpty(userRefs)) {
            return Response.succeed(userVOS);
        }
        List<Integer> userIds = userRefs.stream().map(MesTeamUserRef::getUserId).collect(Collectors.toList());
        List<SysUser> userList = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, userIds));
        userVOS = userList.stream().map(item -> {
            SysUser sysUser = new SysUser();
            sysUser.setId(item.getId());
            sysUser.setRealName(item.getRealName());
            return sysUser;
        }).collect(Collectors.toList());
        return Response.succeed(userVOS);
    }

    /**
     * 删除
     */
    @PostMapping("/del")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> del(@RequestBody List<Integer> ids) {
        List<MesWorkTeam> workTeamDOS = mesWorkTeamService.list(new LambdaQueryWrapper<MesWorkTeam>().in(MesWorkTeam::getId, ids));
        List<MesWorkTeam> errors = workTeamDOS.stream().filter(item -> Const.AUDIT_STATUS_NORMAL.equals(item.getAuditStatus())).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(errors)) {
            return Response.fail("请勿勾选已审核状态班组！");
        }
        ids = ids.stream().distinct().collect(Collectors.toList());
        mesWorkTeamService.removeByIds(ids);
        return Response.succeed();
    }

    /**
     * 导入
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/import")
    @ResponseBody
    public Response<?> importExcel(@RequestParam("file") MultipartFile multipartFile, HttpServletResponse response) throws IOException {
        return mesWorkTeamService.importExcel(multipartFile, response);
    }
}
